package com.hao.tool.util.module.file.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.hao.tool.common.constant.Commons;
import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.common.util.NetworkUtil;
import com.hao.tool.util.component.properties.PropertiesInfo;
import com.hao.tool.util.component.websocket.config.LogConsumer;
import com.hao.tool.util.component.websocket.config.LogMessage;
import com.hao.tool.util.module.file.entity.Message;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-22 21:46
 */
@RestController
@RequestMapping("/rest/text")
public class TextInfoRestController {
    private Logger logger = LoggerFactory.getLogger(TextInfoRestController.class);

    @Autowired
    private PropertiesInfo propertiesInfo;
    @Autowired
    private LogConsumer logConsumer;

    private static Map<String, Message> staticMap = new HashMap<>();

    /**
     * 添加文本文件缓存信息
     *
     * @param textCode 文件码
     * @param content  内容
     * @param request  请求
     * @return
     */
    @PostMapping("/add/{textCode}")
    public LayResponse upload(@PathVariable String textCode, String content,
                              HttpServletRequest request) {
        String userName = (String) request.getAttribute(Commons.SUB_KEY);
        Message message = new Message();
        if (staticMap.containsKey(textCode)) {
            message = staticMap.get(textCode);
        } else {
            message.setCreateTime(LocalDateTime.now());
        }
        message.setMessage(content);
        message.setIpAddress(NetworkUtil.getIpAddress(request));
        message.setUpdateTime(LocalDateTime.now());
        message.setUpdateUser(userName);
        staticMap.put(textCode, message);


        return LayResponse.builder().code(200).build();
    }


    /**
     * 实时推送信息
     *
     * @param content 内容
     * @param request 请求
     * @return
     */
    @PostMapping("/add/push")
    public LayResponse uploadLog(String content,
                                 HttpServletRequest request) {
        String userName = (String) request.getAttribute(Commons.SUB_KEY);
        LogMessage logMessage = new LogMessage();
        logMessage.setMessage(content);
        logMessage.setUsername(userName);
        logMessage.setLogTime(DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN));
        logConsumer.pushLogger(logMessage);

        return LayResponse.builder().code(200).build();
    }

    /**
     * 同步获取信息
     *
     * @param textCode 文件码
     * @return
     */
    @GetMapping("/sync/{textCode}")
    public LayResponse sync(@PathVariable String textCode) {
        Message message = null;
        message = staticMap.get(textCode);
        if (message == null) {
            return LayResponse.builder().code(404).build();
        }
        String updateTimeStr = DateUtil.format(message.getUpdateTime(), DatePattern.NORM_DATETIME_PATTERN);
        String updateUserStr = StringUtils.isNotBlank(message.getUpdateUser()) ? message.getUpdateUser() : "anonymous";

        return LayResponse.builder()
                .msg("信息已于 " + updateTimeStr + " 更新 by [" + updateUserStr
                        + "] on " + message.getIpAddress())
                .data(message.getMessage()).code(200).build();
    }

    /**
     * 同步获取日志信息
     * 日志信息为参数中配置信息
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/sync/log")
    public LayResponse syncLog() throws Exception {
        String updateTimeStr = DateUtil.format(new Date(), DatePattern.NORM_DATETIME_PATTERN);
        String updateUserStr = "anonymous";
        String logFilePath = propertiesInfo.getLocalLogFilePath();
        String logContent = "";
        if (StringUtils.isBlank(logFilePath)) {
            logContent = ("日志地址未配置");
        } else {
            logContent = FileUtil.readUtf8String(new File(logFilePath));
        }
        logger.info("同步获取日志文件「{}」", logFilePath);
        return LayResponse.builder()
                .msg("信息已于 " + updateTimeStr + " 更新 by [" + updateUserStr + "] ")
                .data(logContent).code(200).build();
    }

}
